package com.ellecity06.common.base

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.view.IUiIntent
import com.ellecity06.common.base.view.IUiState
import com.ellecity06.common.ktx.SharedFlowEvents
import com.ellecity06.common.ktx.postEvent
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/24 15:26
 * @des
 */
open class BaseMviViewModel<T : IUiState, D : IUiIntent> : BaseViewModel() {

    //创建意图管道，容量无限大
    val intentChannel = Channel<D>(Channel.UNLIMITED)

    protected val mState = SharedFlowEvents<T>()
    val state = mState.asSharedFlow()


    init {
        viewModelScope.launch {
            //收集意图
            intentChannel.consumeAsFlow().collect {
                collectIntent(it)

            }
        }

    }

    open suspend fun collectIntent(it: D) {}

  protected  fun postState(vararg event:T){
        viewModelScope.launch {
            mState.postEvent(*event)
        }
    }
}